<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>群聊</title>
    <style>
        .message {
            height: 300px;
            border: 1px solid #dddddd;
            width: 90%;
            margin: 30px;
            overflow-y: auto; /* 添加滚动条 */
            padding: 5px;
        }
        .center {
            text-align: center;
            margin: 5px 0;
        }
        .left {
            text-align: left;
            margin: 5px 0;
        }
        .right {
            text-align: right;
            margin: 5px 0;
        }
    </style>
</head>
<body>
<div class="message" id="message"></div>
<div>
    <input type="text" placeholder="请输入" id="txt">
    <input type="button" value="发送" id="send" onclick="sendMsg()">
    <input type="button" value="关闭连接" onclick="closeConn()">
    <input type="button" value="重新连接" onclick="reconnect()">
</div>

<script>
    var socket = new WebSocket("ws://192.168.2.159:8008/room/123/");

    socket.onopen = function (event) {
        showMessage("连接已建立", "center");
    };

    socket.onmessage = function (event) {
        // 显示接收到的消息在左边
        showMessage(event.data, "left");
    };

    socket.onerror = function (event) {
        showMessage("连接出错：" + (event.message || "未知错误"), "center");
    };

    socket.onclose = function (event) {
        showMessage("连接已断开", "center");
    };

    function sendMsg() {
        var tag1 = document.getElementById("txt");
        var message = tag1.value;
        socket.send(message);
        showMessage("你: " + message, "right");
        tag1.value = ""; // 清空输入框
    }

    function closeConn() {
        socket.close();
    }

    function reconnect() {
        window.location.reload();
    }

    function handleKeyPress(event) {
        if (event.keyCode === 13) {
            sendMsg(); // 直接调用 sendMsg 函数
        }
    }

    document.onkeydown = handleKeyPress;

    function showMessage(message, position) {
        var tag = document.createElement("div");
        tag.innerText = message;
        tag.className = position;
        document.getElementById("message").appendChild(tag);
        // 自动滚动到底部
        var messageBox = document.getElementById("message");
        messageBox.scrollTop = messageBox.scrollHeight;
    }
</script>
</body>
</html>
